package com.zk.babala.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.zk.babala.R;
import com.zk.babala.util.HistoryUtil;
import com.zk.babala.util.ScriptUtil;
import com.zk.babala.vo.ChannelVO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;


/**
 * 直播
 */
public class LiveActivity extends AppCompatActivity {
    private long outKeyTime = 0;
    private WebView webView;
    private final List<ChannelVO> channelUrls = new ArrayList<>();
    private ChannelVO currChannel;
    private LinearLayout channelListLayout;
    private ListView channelListView;
    private boolean isChannelListVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.live_activity);
        webView = findViewById(R.id.webViewLive);
        channelListLayout = findViewById(R.id.channelListLayout);
        channelListView = findViewById(R.id.channelListView);
        channelListView.setSelector(R.drawable.list_view_selected);
        WebSettings webSettings = webView.getSettings();
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        webSettings.setMediaPlaybackRequiresUserGesture(false);
        webSettings.setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
        webView.setFocusable(false);
        webView.setWebChromeClient(new WebChromeClient());
        initChannels();
        // 初始化频道列表显示
        initChannelList();

        // 设置 WebViewClient 以便在页面加载完成后执行全屏操作
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 页面加载完成后执行全屏点击操作
                enterFullscreen();
            }
        });
        currChannel = HistoryUtil.getHistoryInstance().getLiveHis();
        play();
    }

    /**
     * 初始化频道列表
     */
    private void initChannels() {
        String mgtvUrl = "https://www.mgtv.com/live/?fpa=1219&fpos=&lastp=ch_home";
        channelUrls.add(new ChannelVO("湖南娱乐", mgtvUrl));
        channelUrls.add(new ChannelVO("湖南电视剧", mgtvUrl));
        channelUrls.add(new ChannelVO("湖南都市", mgtvUrl));
        channelUrls.add(new ChannelVO("湖南电影", mgtvUrl));
        channelUrls.add(new ChannelVO("湖南经视", mgtvUrl));
        channelUrls.add(new ChannelVO("金鹰卡通", mgtvUrl));
        channelUrls.add(new ChannelVO("湖南爱晚", mgtvUrl));
        channelUrls.add(new ChannelVO("金鹰纪实", mgtvUrl));
        channelUrls.add(new ChannelVO("CCTV-1", "https://tv.cctv.com/live/cctv1/"));
        channelUrls.add(new ChannelVO("CCTV-2", "https://tv.cctv.com/live/cctv2/"));
        channelUrls.add(new ChannelVO("CCTV-3", "https://tv.cctv.com/live/cctv3/"));
        channelUrls.add(new ChannelVO("CCTV-4", "https://tv.cctv.com/live/cctv4/"));
        channelUrls.add(new ChannelVO("CCTV-5", "https://tv.cctv.com/live/cctv5/"));
        channelUrls.add(new ChannelVO("CCTV-6", "https://tv.cctv.com/live/cctv6/"));
        channelUrls.add(new ChannelVO("CCTV-7", "https://tv.cctv.com/live/cctv7/"));
        channelUrls.add(new ChannelVO("CCTV-8", "https://tv.cctv.com/live/cctv8/"));
        channelUrls.add(new ChannelVO("CCTV-9 纪录", "https://tv.cctv.com/live/cctvjilu/"));
        channelUrls.add(new ChannelVO("CCTV-10", "https://tv.cctv.com/live/cctv10/"));
        channelUrls.add(new ChannelVO("CCTV-11", "https://tv.cctv.com/live/cctv11/"));
        channelUrls.add(new ChannelVO("CCTV-12", "https://tv.cctv.com/live/cctv12/"));
        channelUrls.add(new ChannelVO("CCTV-13 新闻", "https://tv.cctv.com/live/cctv13/"));
        channelUrls.add(new ChannelVO("CCTV-14 少儿", "https://tv.cctv.com/live/cctvchild/"));
        channelUrls.add(new ChannelVO("CCTV-15 音乐", "https://tv.cctv.com/live/cctv15/"));
        channelUrls.add(new ChannelVO("CCTV-17 农业", "https://tv.cctv.com/live/cctv17/"));
    }

    public void play() {
        if (channelUrls.isEmpty()) {
            Toast.makeText(this, "频道列表为空", Toast.LENGTH_LONG).show();
            return;
        }
        if (currChannel == null) {
            currChannel = channelUrls.get(0);
        }
        HistoryUtil.getHistoryInstance().saveLiveHis(currChannel);
        // 访问网页
        webView.loadUrl(currChannel.getUrl());
    }

    /**
     * 播放下一个频道
     */
    public void playNext() {
        if (currChannel != null) {
            currChannel = channelUrls.get((channelUrls.indexOf(currChannel) + 1) % channelUrls.size());
        }
        play();
    }

    /**
     * 播放上一个频道
     */
    public void playPre() {
        if (currChannel != null) {
            currChannel = channelUrls.get((channelUrls.indexOf(currChannel) - 1 + channelUrls.size()) % channelUrls.size());
        }
        play();
    }

    /**
     * 进入全屏播放模式
     */
    private void enterFullscreen() {
        // 从assets目录读取JavaScript文件；
        String script;
        if (currChannel.getUrl().startsWith("https://www.mgtv.com")) {
            script = StrUtil.format(ScriptUtil.getMgtvScripts(), currChannel.getName());
        } else {
            script = ScriptUtil.getFullScreenScripts();
        }
        // 执行JavaScript
        webView.evaluateJavascript(script, value -> {
            // 处理JavaScript执行结果
        });

    }

    /**
     * 初始化频道列表显示
     */
    private void initChannelList() {
        List<String> channelNames = channelUrls.stream().map(ChannelVO::getName).collect(Collectors.toList());
        // 创建适配器并设置给 ListView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                channelNames) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView text = view.findViewById(android.R.id.text1);
                text.setTextColor(Color.WHITE);
                return view;
            }
        };
        channelListView.setAdapter(adapter);

        // 设置频道列表点击事件
        channelListView.setOnItemClickListener((parent, view, position, id) -> {
            if (position >= 0 && position < channelUrls.size()) {
                currChannel = channelUrls.get(position);
                play();
                toggleChannelList(); // 选择后隐藏频道列表
            }
        });
    }

    /**
     * 切换频道列表显示状态
     */
    private void toggleChannelList() {
        isChannelListVisible = !isChannelListVisible;
        channelListLayout.setVisibility(isChannelListVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    // 右键下一频道
                    playNext();
                    return true;

                case KeyEvent.KEYCODE_DPAD_LEFT:
                    // 左键上一频道
                    playPre();
                    return true;

                case KeyEvent.KEYCODE_ENTER:
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    // 确认键显示/隐藏频道列表
                    toggleChannelList();
                    return true;

                case KeyEvent.KEYCODE_BACK:
                    // 如果频道列表显示则先隐藏频道列表
                    if (isChannelListVisible) {
                        toggleChannelList();
                        return true;
                    }
                    // 退出应用
                    if ((System.currentTimeMillis() - outKeyTime) > 1000) {
                        Toast.makeText(this, "再按一次退出播放！", Toast.LENGTH_SHORT).show();
                        outKeyTime = System.currentTimeMillis();
                        return true;
                    }
                    break;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


}
